package com.miage.pki.service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.miage.pki.obj.User;

@Service
public class UserServiceImpl implements UserService {
    
    Connection connection;
    Statement mysql;
    
    public UserServiceImpl(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost/pkisecurity?" + "user=root&password=secret");
            mysql = connection.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public boolean CreateUser(String username, String password, String last_name, String first_name, String dn, String email){
        try {
            mysql.executeUpdate("INSERT INTO `pkisecurity`.`users` (`username`, `password`, `last_name`, `first_name`, `id_role`, `enabled`, `dn`, `email`, `state`) VALUES ('"+username+"', md5('"+password+"'), '"+last_name+"', '"+first_name+"', 2, 0, '"+dn+"', '"+email+"', 0)");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }    
    
    public List<User> ListUsers(){
        ArrayList<User> al = new ArrayList<User>();
        ResultSet rs;
        
        try {
             rs = mysql.executeQuery("SELECT username, last_name, first_name, id_role, enabled, dn, email FROM users WHERE `state`=1");
             
             while(rs.next()){
                 if(!rs.getString(1).equals("admin")){
                     User u = new User();
                     
                     u.setUsername(rs.getString(1));
                     u.setLast_name(rs.getString(2));
                     u.setFirst_name(rs.getString(3));
                     u.setRole(rs.getString(4));
                     u.setEnabled(rs.getString(5));
                     u.setDn(rs.getString(6));
                     u.setEmail(rs.getString(7));
                     
                     al.add(u);
                 }
             }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        return al;
    }
    
    public List<User> ListWaitingUsers(){
        ArrayList<User> al = new ArrayList<User>();
        ResultSet rs;
        
        try {
             rs = mysql.executeQuery("SELECT username, last_name, first_name, id_role, enabled, dn, email FROM users WHERE `state`=0");
             
             while(rs.next()){
                 if(!rs.getString(1).equals("admin")){
                     User u = new User();
                     
                     u.setUsername(rs.getString(1));
                     u.setLast_name(rs.getString(2));
                     u.setFirst_name(rs.getString(3));
                     u.setRole(rs.getString(4));
                     u.setEnabled(rs.getString(5));
                     u.setDn(rs.getString(6));
                     u.setEmail(rs.getString(7));
                     
                     al.add(u);
                 }
             }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        return al;
    }
    
    public List<User> ListDeletedUsers(){
        ArrayList<User> al = new ArrayList<User>();
        ResultSet rs;
        
        try {
             rs = mysql.executeQuery("SELECT username, last_name, first_name, id_role, enabled, dn, email FROM users WHERE `state`=2");
             
             while(rs.next()){
                 if(!rs.getString(1).equals("admin")){
                     User u = new User();
                     
                     u.setUsername(rs.getString(1));
                     u.setLast_name(rs.getString(2));
                     u.setFirst_name(rs.getString(3));
                     u.setRole(rs.getString(4));
                     u.setEnabled(rs.getString(5));
                     u.setDn(rs.getString(6));
                     u.setEmail(rs.getString(7));
                     
                     al.add(u);
                 }
             }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        return al;
    }
    
    public boolean enableUser(String username){
        try {
            mysql.executeUpdate("UPDATE `users` SET `enabled`=1, `state`=1 WHERE `username`='"+username+"'");
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
    
    public boolean disableUser(String username){
        try {
            mysql.executeUpdate("UPDATE `users` SET `enabled`=0, `state`=2 WHERE `username`='"+username+"'");
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
    
    public boolean deleteWaitingUser(String username){
        try {
            mysql.executeUpdate("DELETE FROM `users` WHERE `username`='"+username+"' AND `state`=0");
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    
    public User getUser(String username){
        User u = new User();
        
        try {
            ResultSet rs = mysql.executeQuery("SELECT username, last_name, first_name, id_role, enabled, dn, email FROM users WHERE `username`='"+username+"' AND `state`=1");
            
            if(rs.next()){
                u.setUsername(rs.getString(1));
                u.setLast_name(rs.getString(2));
                u.setFirst_name(rs.getString(3));
                u.setRole(rs.getString(4));
                u.setEnabled(rs.getString(5));
                u.setDn(rs.getString(6));
                u.setEmail(rs.getString(7));
            }
       } catch (Exception e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
        
       return u;
    }
    
    public boolean modifyUser(String username, String password){
        try {
            mysql.executeUpdate("UPDATE `users` SET `password`=md5('"+password+"') WHERE `username`='"+username+"'");
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
    
    public String encode(String password) {

        byte[] uniqueKey = password.getBytes();
        byte[] hash = null;

        try {
            hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
        } catch (NoSuchAlgorithmException e) {
            throw new Error("No MD5 support in this VM.");
        }

        StringBuilder hashString = new StringBuilder();
        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(hash[i]);
            if (hex.length() == 1) {
                hashString.append('0');
                hashString.append(hex.charAt(hex.length() - 1));
            } else {
                hashString.append(hex.substring(hex.length() - 2));
            }
        }
        return hashString.toString();
    }


    
    public String getUserKeyStorePassword(String username){
        try {
            ResultSet rs = mysql.executeQuery("SELECT dn FROM users WHERE `username`='"+username+"'");
            if(rs.next()){
                String s = rs.getString(1);
                return encode("salt"+s+"me");
            }
       } catch (Exception e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       return null;
    }
    
    public User getUserFormDN(String dn){
        User u = null;
        try {
            ResultSet rs = mysql.executeQuery("SELECT username, last_name, first_name, id_role, enabled, dn, email FROM users WHERE `dn`='"+dn+"'");
            
            if(rs.next()){
                u = new User();
                u.setUsername(rs.getString(1));
                u.setLast_name(rs.getString(2));
                u.setFirst_name(rs.getString(3));
                u.setRole(rs.getString(4));
                u.setEnabled(rs.getString(5));
                u.setDn(rs.getString(6));
                u.setEmail(rs.getString(7));
            }
       } catch (Exception e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       return u;
    }
}
